<template>
  <div>
    <!--          搜索框-->
    <el-row :gutter="20">
      <el-col :xs="24" :sm="12" :md="8" :lg="6">
        <el-input v-model="formData1.username" placeholder="请输入名称" suffix-icon="el-icon-search"></el-input>
      </el-col>
      <el-col :xs="24" :sm="12" :md="8" :lg="6">
        <el-input v-model="formData1.email" placeholder="请输入邮箱" suffix-icon="el-icon-message"></el-input>
      </el-col>
      <el-col :xs="24" :sm="12" :md="8" :lg="6">
        <el-input v-model="formData1.address" placeholder="请输入地址" suffix-icon="el-icon-location-information"></el-input>
      </el-col>
      <el-col :xs="24" :sm="12" :md="4" :lg="6" class="button-container">
        <el-button type="primary" @click="search">搜索</el-button>
        <el-button type="info" @click="reset">重置</el-button>
      </el-col>
    </el-row>
    <!--          按钮-->
    <div style="margin: 10px 0">
      <el-button type="success" plain  @click="insert" >新增<i class="el-icon-circle-plus-outline" style="margin-left: 5px"></i>
      </el-button>
      <el-button type="danger" plain @click="batchDelete">批量删除
        <i class="el-icon-delete" style="margin-left: 5px"></i></el-button>
      <el-button type="info" plain >导入<i class="el-icon-upload2" style="margin-left: 5px"></i></el-button>
      <el-button type="warning" plain>导出<i class="el-icon-download" style="margin-left: 5px"></i></el-button>
    </div>
    <!--          border stripe 斑马线
                   :header-row-style = "headerBg" 表头颜色
    -->
    <el-table ref="tableName"  :data="tableData" border stripe :header-cell-class-name="headerBg"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column  label="ID" width="120">
        <template scope="scope">
          <span>{{ (page - 1) * limit + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="120">
        <template slot-scope="{ row }">
          {{ row.username || '--' }}
        </template>
      </el-table-column>
      <el-table-column prop="nickname" label="昵称">
        <template slot-scope="{ row }">
          {{ row.nickname || '--' }}
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱">
        <template slot-scope="{ row }">
          {{ row.email || '--' }}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="电话">
        <template slot-scope="{ row }">
          {{ row.phone || '--' }}
        </template>
      </el-table-column>
      <el-table-column prop="address" label="地址">
        <template slot-scope="{ row }">
          {{ row.address || '--' }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-link icon="el-icon-edit" :underline="false" style="margin-right: 10px;color: #14c2c2"
                   @click="edit(scope.row.id)">编辑
          </el-link>
          <el-link icon="el-icon-delete" :underline="false" style="margin-left: 20px;color: #46a6fe"
                   @click="remove(scope.row.id)">删除
          </el-link>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="dialogVisible" title="编辑用户信息" :style="{ width: '100%' }">
      <el-form ref="formRules" :model="formData" :rules="rules" label-width="100px" >
        <el-form-item label="用户名：" prop="username">
          <el-input v-model="formData.username"></el-input>
        </el-form-item>
        <el-form-item label="昵称：" prop="nickname">
          <el-input v-model="formData.nickname"></el-input>
        </el-form-item>
        <el-form-item label="邮箱：" prop="email">
          <el-input v-model="formData.email"></el-input>
        </el-form-item>
        <el-form-item label="电话：" prop="phone" :maxlength="11" :minlength="1" clearable show-word-limit>
          <el-input v-model="formData.phone"></el-input>
        </el-form-item>
        <el-form-item label="地址：" prop="address">
          <el-input v-model="formData.address"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateOrInsertData()" :loading="isLoading">确 定</el-button>
      </div>
    </el-dialog>
    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page= "this.page"
          :page-sizes="[10, 15, 20, 25]"
          :page-size= "this.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total=total>
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {allUserMessage, deleteById, deleteByIds, updateUserById} from "@/api/user";

export default {
  name: "User",
  data() {
    return {
      //校验规则
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' }
        ],
        email: [
          {required: true, message: '请输入邮箱地址', trigger: 'change'},
          {type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}
        ],
        phone: [{
          required: true,
          message: '请输入手机号',
          trigger: 'change'
        }, {
          pattern: /^1(3|4|5|7|8|9)\d{9}$/,
          message: '手机号格式错误',
          trigger: 'blur'
        }],
        address: [
          { required: true, message: '请输入地址', trigger: 'blur' }
        ]
      },
      //加载
      isLoading: false,
      // 批量删除选中ids
      selectedIds: [],
      //控制弹窗
      dialogVisible: false,
      //编辑后的数据
      tableData: [],
      formData: {
        id: '',
        username: '',
        nickname: '',
        email: '',
        phone: '',
        address: '',
      },
      formData1: {
        id: '',
        username: '',
        nickname: '',
        email: '',
        phone: '',
        address: '',
      },
      page: 1,
      limit: 10,
      total: 0,
      logoTextShow: true,
      headerBg: 'headerBg'
    }
  },
  methods: {
    // 模糊查询:
    search(){
      let message = {
        username:this.formData1.username,
        email:this.formData1.email,
        address:this.formData1.address,
        page:this.page,
        limit:this.limit
      };
      allUserMessage(message).then(res => {
        this.tableData = res.data;
        this.total = res.total;
      });
    },
    //reset 重置清空
    reset(){
      this.formData = {
        username: '',
        email: '',
        address: ''
      }
      this.loaded()
    },
    //批量删除
    handleSelectionChange(selection) {
      this.selectedIds = selection.map(item => item.id);
    },
    batchDelete() {
      if (this.selectedIds.length === 0) {
        this.$message.warning('请先选择要删除的行！');
        return;
      }
      this.$confirm('是否删除选中行？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteByIds(this.selectedIds).then(res => {
          if (res.code == 200) {
            this.loading = false;
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            // 在这里调用 reload() 方法来刷新表格
            this.loaded()
          }
        });
        // 在此处调用删除接口并传入当前选中的 ID 数组
        // 删除成功后重新加载表格数据
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //新增用户信息
    insert(){
      this.dialogVisible = true
      // 清空formData对象
      this.formData = {}
      this.$refs['formRules'].resetFields();
    },
    //打开弹窗显示这条信息
    edit(id){
      // 根据id获取当前行的数据
      const currentRow = this.tableData.find(item => item.id === id)
      console.log(currentRow)
      // 将当前行的数据赋值给formData
      this.formData = Object.assign({}, currentRow)
      // 打开弹窗
      this.dialogVisible = true
      //清空表单
      this.$refs['formRules'].resetFields();
    },
    //修改这条信息
    updateOrInsertData(){
      // 校验
      this.$refs.formRules.validate(valid => {
        if (valid) {
          // 数据校验通过，可以提交数据
          this.isLoading = true
          const user = this.formData;
          setTimeout(() => {
            this.isLoading = false;
            updateUserById(user).then(res=> {
              if (res.code == 200) {
                this.loading = false;
                if (user.id != null){
                  this.$message({
                    type: 'success',
                    message: '编辑成功!'
                  });
                }else {
                  this.$message({
                    type: 'success',
                    message: '新增成功!'
                  });
                }
                // 关闭弹窗
                this.dialogVisible = false
                // 在这里调用 reload() 方法来刷新表格
                this.loaded()
                // 清空formData对象
                this.formData = {}
              }
            })
          }, 1000);
        } else {
          // 数据校验不通过，提示错误信息
          // 清除表单验证状态
          return false;
        }
      });
    },
    //删除这条信息
    remove(id) {
      let param = {id:id}
      this.$confirm('此操作将永久删除该异常原因, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        deleteById(param).then(res => {
          if (res.code == 200) {
            this.loading = false;
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            // 在这里调用 reload() 方法来刷新表格
            this.loaded()
          }
        });
      })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
    },
    loaded() {
      let page = {page:this.page,limit:this.limit};
      allUserMessage(page).then(res => {
        this.tableData = res.data;
        this.total = res.total;
      });
    },
    // request.post("http://localhost:9999/user/message/allUserMessage", {
    //   page: this.page,
    //   limit: this.limit
    // }).then(res =>{
    //   this.tableData = res.data
    //   this.total = res.total
    // })
    handleSizeChange(limit){
      this.limit = limit
      this.loaded(this.limit)
    },
    handleCurrentChange(page){
      this.page = page
      this.loaded(this.page)
    },
  },
  created() {
    this.loaded();
  },
  mounted() {
    // 引用表单组件
    this.form = this.$refs.form;
  }
}
</script>

<style scoped>
.headerBg {
  background: #ccc !important;
}
.button-container {
  display: flex;
  justify-content: flex-end;
}
.el-pagination {
  display: flex;
  justify-content: flex-end;
}

</style>
